package com.lijin.batchsys.framework.control;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

import com.lijin.batchsys.framework.common.BatchSysException;
import com.lijin.batchsys.framework.dao.model.JobInfo;

public class BatchSysConcurrentJob extends BatchSysAbstractJob {
	
	private static final int CON_NUM = 5;
	
	public BatchSysConcurrentJob(JobInfo jobInfo) {
		super(jobInfo);
	}

	private static final Logger logger = Logger.getLogger(BatchSysConcurrentJob.class);

	@Override
	protected void doExecute(final BatchExecContext batchCtx) {
		
		ExecutorService service = Executors.newFixedThreadPool(CON_NUM);
		for (final BatchSysStep step : steps) {
			service.submit(new Runnable() {
				@Override
				public void run() {
					handleStep(step, batchCtx);
				}
			});
		}
		
		service.shutdown();
		
		try {
			while (!service.awaitTermination(5, TimeUnit.SECONDS)) {
				logger.info("仍然还有步骤在执行...");
			}
		} catch (InterruptedException e) {
			logger.error("并发任务执行出错", e);
			throw new BatchSysException("并发任务执行出错", e);
		}
	}

}
